import type { IValues } from 'aoe';
import { computed, type Ref } from 'vue';
import { arr_push, arr_splice, obj_update } from 'aoe';

export const arr_splice_ref: <T = unknown>(
  arr: Ref<T[] | undefined>,
  start: number,
  deleteCount?: number,
  ...items: T[]
) => Array<T> = (arr, start, deleteCount = 1, ...items) =>
  (arr.value = arr_splice(arr.value, start, deleteCount, ...items));


export const arr_push_ref: <T = unknown>(
  arr: Ref<T[] | undefined>,
  ...items: T[]
) => Array<T> = (arr, ...items) => (arr.value = arr_push(arr.value, ...items));


// noinspection JSUnusedGlobalSymbols
/**
 * # { ...vs, [name]: v }
 */
export const obj_update_ref = <R = unknown, T extends string = string>(
  vs: Ref<IValues | undefined>,
  name: T,
  v: R,
) => name && (vs.value = obj_update(vs.value, name, v));

export const usePartOf = <T>(key: string, rObj: Ref) => {
  return computed<T>({
    get: () => rObj?.value?.[key] as T,
    set: (val: T) => <T>obj_update_ref(rObj, key, val),
  });
}
